package com.hsylient.javase.chapter14.signature;


import cn.hutool.core.codec.Base64Decoder;
import cn.hutool.core.codec.Base64Encoder;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.asymmetric.Sign;
import cn.hutool.crypto.asymmetric.SignAlgorithm;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;

import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.Signature;

@Slf4j
public class SignatureTest {

    @Test
    @SneakyThrows
    public void testSignFromJdk() {

        // 初始化非对称加密的算法
        KeyPairGenerator rsa = KeyPairGenerator.getInstance("RSA");
        // 公私钥的长度
        rsa.initialize(1024);
        // 生成公私钥
        KeyPair keyPair = rsa.genKeyPair();
        // 将公钥打印，用来验证签名
        byte[] publicKey = keyPair.getPublic().getEncoded();
        log.info("字符串公钥：{}", Base64Encoder.encodeUrlSafe(publicKey));

        // 签名用到的算法名字
        Signature signature = Signature.getInstance("SHA256withRSA");
        // 用那个私钥签名
        signature.initSign(keyPair.getPrivate());
        // 签名的内容是什么
        signature.update("我想要漂亮的姑娘".getBytes());
        // 签名后的字节数组
        byte[] sign = signature.sign();

        log.info("[我想要漂亮的姑娘]经过签名后的字节数组编码为字符串：{}", Base64Encoder.encodeUrlSafe(sign));

        // -----------------------验签------------------------

        // 公钥：MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCCeI2akL0fUd8RzM6FEt_pTao94apOx7_NMKnHAYhHX_bDHruD796vWbb95niqEOdn0tMPFMgNaR_Fz_12obuW_v6lzqv66YDApWY-UBFHn3u9f-oM0OGKZW1nmprT4Zfiulx2D1GsNESpDvQNyaLzVcgISSNXhDSBo60c6IUHBwIDAQAB
        // 签名：XJjfqkKSm8jXwdJKmAhwC461ptRP3rFBxxxacgi9vlb_oCJ1Q4NBJg0MclmaGD9hksy1wWnJvGhLb_XQI0XKTrv3KMq9JzSTifvmSh2u6oXeCyaAgVIQgOIr21G90Ky1GqPu7mFLzk1V3SRzfaa-if1-NyjLllQ4LIPr6gDmwcs
        signature.initVerify(keyPair.getPublic());
        signature.update("我想要漂亮的姑娘".getBytes());
        boolean verify = signature.verify(sign);
        log.info(Boolean.toString(verify));
    }

    @Test
    @SneakyThrows
    public void testHutool() {
        // 签名内容
        byte[] data = "我想要漂亮的姑娘".getBytes();
        // 签名算法
        Sign sign = SecureUtil.sign(SignAlgorithm.SHA256withRSA, null, "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCCeI2akL0fUd8RzM6FEt_pTao94apOx7_NMKnHAYhHX_bDHruD796vWbb95niqEOdn0tMPFMgNaR_Fz_12obuW_v6lzqv66YDApWY-UBFHn3u9f-oM0OGKZW1nmprT4Zfiulx2D1GsNESpDvQNyaLzVcgISSNXhDSBo60c6IUHBwIDAQAB");
        //验证签名
        boolean verify = sign.verify(data, Base64Decoder.decode("XJjfqkKSm8jXwdJKmAhwC461ptRP3rFBxxxacgi9vlb_oCJ1Q4NBJg0MclmaGD9hksy1wWnJvGhLb_XQI0XKTrv3KMq9JzSTifvmSh2u6oXeCyaAgVIQgOIr21G90Ky1GqPu7mFLzk1V3SRzfaa-if1-NyjLllQ4LIPr6gDmwcs"));
        // 打印签名结果
        log.info(Boolean.toString(verify));

        log.info("SHA256输出结果长度：{}", "E3B0C44298FC1C149AFBF4C8996FB92427AE41E4649B934CA495991B7852B855".length());
    }
}
